import java.awt.*;
import java.awt.font.*;
import javax.swing.*;
  
public class DrawingText extends JPanel
{
    Font font;
    String text;
  
    public DrawingText()
    {
        font = new Font("lucida bright regular", Font.PLAIN, 24);
        text = "centered text";
    }
  
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        int w = getWidth();
        int h = getHeight();
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        float width = (float)font.getStringBounds(text, frc).getWidth();
        LineMetrics lm = font.getLineMetrics(text, frc);
        float height = lm.getAscent() + lm.getDescent();
        float sx = (w - width)/2;
        float sy = (h + height)/2 - lm.getDescent();
        g2.drawString(text, sx, sy);
    }
  
    public static void main(String[] args)
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new DrawingText());
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
    }
}